package com.project.hqshorttaxi.service.impl;

import com.project.hqshorttaxi.dto.RoleParam;
import com.project.hqshorttaxi.entity.Login;
import com.project.hqshorttaxi.entity.Role;
import com.project.hqshorttaxi.mapper.RoleMapper;
import com.project.hqshorttaxi.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Role getById(Integer id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list(RoleParam param) {
        Example example = new Example(Login.class);
        Example.Criteria c = example.createCriteria();
        if (!StringUtils.isEmpty(param.getRoleName())) {
            c.andLike("userName", "%" + param.getRoleName() + "%");
        }
        c.andEqualTo("deleteFlag", 0);
        example.orderBy("createTime").desc();
        List<Role> list = roleMapper.selectByExample(example);
        return list;
    }

    @Override
    public Role getByRoleId(Integer roleId) {
        Example example = new Example(Role.class);
        Example.Criteria c = example.createCriteria();
        c.andEqualTo("roleId", roleId);
        c.andEqualTo("deleteFlag", 0);
        List<Role> list = roleMapper.selectByExample(example);
        return list.size() == 0 ? null : list.get(0);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(Role entity) throws Exception {
        roleMapper.insertSelective(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Role entity) throws Exception {
        roleMapper.updateByPrimaryKeySelective(entity);
    }
}
